import ConfigParser

from connection_rules import ConnectionRules
from host_group import HostGroup
from connections import Connections
from database import Database

class ConnTrack():
	def __init__(self):
		self.db = Database()

		# Load conntrack rules		
		self.connection_rules = []
		for rule_id in self.load_rules():
			self.connection_rules.append(ConnectionRules(rule_id))

		self.connections = Connections()

	def load_rules(self):
		rules = []
		sql="SELECT idconnection_rules FROM connection_rules ORDER BY connection_rules.order"
		res = self.db.execute(sql, "tuple")
		for id in res:
			rules.append(id[0])

		return rules


	def get_proxy(self, src, dst):
		for rule in self.connection_rules:
			if rule.match_src(src) and rule.match_dst(dst):
				print src + " -> " + dst + " : Rule " + str(rule.id) + " match!"
				if rule.action == "allow":
					if rule.ct_enable:
						print "Conntrack Enabled"
						# Follow connection tracking if proxy is into rule.proxygroup
						if self.connections.exists(src, dst):
							return self.connections.get_proxy(src, dst)	
						else:
							new_proxy = rule.get_proxy()
							if new_proxy:
								# Store connection in connection	
								self.connections.set(src, dst, new_proxy)
								return new_proxy
					else:	
						new_proxy = rule.get_proxy()
						if new_proxy:
							return new_proxy
				return None
